# -*- coding: utf-8 -*-
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as ec
from scrapy.http.response.html import HtmlResponse
from selenium.webdriver.common.by import By
from selenium import webdriver
from scrapy import signals
import time

class SeleniumDownloaderMiddleware(object):
    def __init__(self):
        self.driver = webdriver.Chrome(r'D:\chrome\Google\Chrome\Application\chromedriver')

    @classmethod
    def from_crawler(cls, crawler):
        # This method is used by Scrapy to create your spiders.
        s = cls()
        crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
        return s

    def process_request(self, request, spider):

        pass

    def process_response(self, request, response, spider):
        if request.url == 'https://cd.fang.com/':
            self.driver.get(request.url)
            wait = WebDriverWait(self.driver, timeout=10)
            wait.until(ec.visibility_of_element_located((By.XPATH, '//*[@id="dsy_H01_03"]/div[1]//a'))).click()
            source = self.driver.page_source
            response = HtmlResponse(url=self.driver.current_url, body=source, encoding='utf-8', request=request)
            return response
        else:
            print(request.url)
            self.driver.get(request.url)
            time.sleep(2)
            source = self.driver.page_source
            response = HtmlResponse(url=self.driver.current_url, body=source, encoding='utf-8', request=request)
            return response


    def process_exception(self, request, exception, spider):
        # Called when a download handler or a process_request()
        # (from other downloader middleware) raises an exception.

        # Must either:
        # - return None: continue processing this exception
        # - return a Response object: stops process_exception() chain
        # - return a Request object: stops process_exception() chain
        pass

    def spider_opened(self, spider):
        spider.logger.info('Spider opened: %s' % spider.name)